export default {
  namespaced: true,
  state: {
    // 商品列表
    //prods: [],
    // 购物车
    carts: [],
  },
  getters: {
    // 计算总价
    getTotalPrice(state) {
      let total = 0;
      state.carts.forEach((item) => {
        total += item.price * item.number;
      });
      return total.toFixed(2);
    },
    // 计算总数量
    getTotalNum(state) {
      let total = 0;
      state.carts.forEach((item) => {
        total += item.number;
      });
      return total;
    },
  },
  actions: {},
  mutations: {
    // 清空购物车
    clearCart(state) {
      state.carts = [];
    },
    // 添加商品到购物车
    addCart(state, payload) {
      const index = state.carts.findIndex((item) => item.id === payload.id);
      if (index === -1) {
        payload.number = 1;
        state.carts.push(payload);
      } else {
        state.carts[index].number++;
      }
    },
    // 从购物车中删除商品
    removeCart(state, id) {
      const index = state.carts.findIndex((item) => item.id === id);
      if (index !== -1) {
        state.carts.splice(index, 1);
      }
    },
  },
};
